<template>
  <el-dialog
    :model-value="roleDialogVisible"
    title="分配角色"
    width="30%"
    @close="handleClose"
  >
    <el-form :model="form" label-width="80px">
      <!-- 这里必须有el-form这个标签否则会报错 -->
      <el-form-item label="用户名">
        <el-input v-model="form.name" disabled />
      </el-form-item>

      <el-form-item label="角色列表">
        <el-checkbox-group v-model="form.type">
          <el-checkbox
            v-for="role in roleNameList"
            :key="role.id"
            :label="role.id"
            :title="role.roleRemark"
            >{{ role.roleName }}</el-checkbox
          >
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">Cancel</el-button>
        <el-button type="primary" @click="handleConfirm">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { defineEmits, defineProps, ref, watch } from 'vue'
import { assignRoleByUserId } from '@/api/authority.js'
import { ElMessage } from 'element-plus'
const form = ref({
  name: '',
  type: []
})

const emits = defineEmits(['update:modelValue', 'initTableList'])
/* const props = defineProps({
  roleDialogVisible: {
    default: false,
    type: Boolean
  },
  roleDialogUserName: {
    type: String,
    default: ''
  },
  roleNameList: {
    type: [],
    default: []
  },
  userRoleList: {
    type: [],
    default: []
  }
}) */

const props = defineProps([
  'roleDialogVisible',
  'roleDialogUser',
  'roleNameList',
  'userRoleList'
])
watch(
  [() => props.roleDialogUserName, () => props.userRoleList],
  () => {
    form.value.name = props.roleDialogUser.username
    form.value.type = props.userRoleList
  },
  { deep: true, immediate: true }
)

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = async () => {
  const roleIds = form.value.type
  const userId = props.roleDialogUser.id
  try {
    await assignRoleByUserId(userId, roleIds)
    ElMessage({
      type: 'success',
      duration: 1500,
      message: '分配成功'
    })
    handleClose()
    emits('initTableList')
  } catch (error) {
    ElMessage({
      type: 'error',
      duration: 1500,
      message: error
    })
  }
}
</script>

<style lang="scss" scoped></style>
